package eg.ci.mvn.service.core.config.log4j2;


import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.helpers.MessageFormatter;

import java.io.Serializable;

@SuppressWarnings("unused")
@Plugin(
        name = "WarningSignal",
        category = "Core",
        elementType = "appender",
        printObject = true
)
public class WarningSignalAppender extends AbstractAppender {

    private static final String msg = "{}：【{}】 运行告警:<font color=\"warning\"></font>\n" +
            ">版本:<font color=\"info\">{}</font>\n" +
            ">主机:<font color=\"info\">{}</font>\n" +
            ">地址:<font color=\"info\">{}</font>\n" +
            ">告警原因:<font color=\"warning\"> {} </font>";


    protected WarningSignalAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, Property[] properties) {
        super(name, filter, layout, ignoreExceptions, properties);
    }

    @Override
    public void append(LogEvent logEvent) {
        try {
            new Thread(() -> sendMsg(logEvent)).start();
        } catch (Exception e) {
        }
    }

    private void sendMsg(LogEvent logEvent) {
        if (logEvent == null) return;

        if (Level.ERROR == logEvent.getLevel()) {
            String traceId = logEvent.getContextData().getValue("X-B3-TraceId");
            try {
                StringBuilder sb = new StringBuilder();
                if (logEvent.getMessage() != null) {
                    sb.append(logEvent.getMessage().getFormattedMessage());
                }
                if (logEvent.getThrown() != null) {
                    sb.append("\n");
                    for (StackTraceElement stackTraceElement : logEvent.getThrown().getStackTrace()) {
                        sb.append(stackTraceElement.toString()).append("\n");
                    }
                }
                sendMessage(sb);
            } catch (Exception e) {
            }
        }
    }


    /**
     * 发送告警消息
     * @param sb
     */
    private void sendMessage(StringBuilder sb){
//        String applicationName = SpringUtil.getApplicationName();
//        SystemConfig systemConfig = SpringUtil.getBean(SystemConfig.class);
//        String  alarmProject = systemConfig.getAlarmProject();
//        String message = format(msg,
//                alarmProject, applicationName,
//                SpringUtil.getBean(GitRepositoryState.class).getCustVersionName(),
//                SpringUtil.getBean(GitRepositoryState.class).getHostName(),
//                SpringUtil.getBean(GitRepositoryState.class).getHostAddress(),
//                sb.toString().length() > 1001 ? sb.substring(0, 1000) : sb.toString());
//        if(systemConfig.isEPWeChatAlarmKeyOpen()){
//            String  EPWeChatAlarmKey = systemConfig.getEPWeChatAlarmKey();
//            SpringUtil.getBean(EPWeChatAlarmUtil.class).setMarkdownMessageAlarm(EPWeChatAlarmKey,message);
//        }
    }


    public static String format(String template, Object... params) {
        if (params == null || params.length == 0)
            return template;
        return MessageFormatter.arrayFormat(template, params).getMessage();
    }

    @PluginFactory
    public static WarningSignalAppender createAppender(@PluginAttribute("name") String name,
                                                       @PluginElement("Filter") final Filter filter,
                                                       @PluginElement("Layout") Layout<? extends Serializable> layout,
                                                       @PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
                                                       @PluginElement("properties") Property[] properties) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImpl");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new WarningSignalAppender(name, filter, layout, ignoreExceptions, properties);
    }
}
